class User < ActiveRecord::Base
  has_and_belongs_to_many :roles
  
  validates_confirmation_of :password, :message => "no coincide"
  validates_presence_of :name, :last_name, :email, :username, :rut, :message => "no puede estar en blanco"
  validates_presence_of  :password, :on => :create, :message => "no puede estar en blanco"
  validates_uniqueness_of :email, :username, :rut, :message => "ya existe"
  validates :email, :email_format => true
  validates :rut, :rut_format => true 
  validates_format_of :rut,
                        :with => /\A(\d{1,3})\.(\d{1,3})\.(\d{1,3})\-(k|\d{1})\Z/i,
                        :message => "rut incorrecto"
  
  
  # Include default devise modules. Others available are:
  # :token_authenticatable, :encryptable,  and :omniauthable, :validatable
  devise :confirmable,:lockable, :timeoutable,:database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :email, :password, :password_confirmation, :remember_me,:name, :last_name, :username,:rut,:login, :role_ids
  # Virtual attribute for authenticating by either username or email
  # This is in addition to a real persisted field like 'username'
  attr_accessor :login
  
  def role?(role)
      return !!self.roles.find_by_name(role.to_s.camelize)
  end
  
  def self.search(search)
    if search
      where('name LIKE ?', "%#{search}%")
    else
      scoped
    end
  end
  
  protected

   def self.find_for_database_authentication(warden_conditions)
     conditions = warden_conditions.dup
     login = conditions.delete(:login)
     where(conditions).where(["lower(username) = :value OR lower(email) = :value OR lower(rut) = :value", { :value => login.downcase }]).first
   end
   
end
